package com.hgkj.cloud.customer.controller;

import com.hgkj.cloud.customer.common.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import it.sauronsoftware.jave.MultimediaInfo;
import it.sauronsoftware.jave.Encoder;

import java.io.File;
import java.util.*;


@CrossOrigin
@RestController
@RequestMapping("/common")
public class AdminCommonController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${upload.file.path}")
    private String uploadFilePath;

    @Value("${upload.file.testPath}")
    private String uploadTestPath;
    /**
     * 上传文件
     * @param uploadFiles
     * @param uuid
     * @param type
     * @param classification
     * @return
     */
    @RequestMapping(value = "/uploadFile",method =  RequestMethod.POST)
    @ResponseBody
    public ResponseData uploadFile(@RequestParam("uploadFile") MultipartFile uploadFiles[],
                                   @RequestParam String uuid, @RequestParam String type,
                                   String classification) {
        logger.info("=====================uploadFile=========================");
        ResponseData reData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> urlList  = new ArrayList<String>();
        if (uuid == null || "".equals(uuid)) {
            reData.setCode(-1);
            reData.setMsg("uuid为空!");
            return reData;
        }
        if (type == null || "".equals(type)) {
            reData.setCode(-1);
            reData.setMsg("type为空!");
            return reData;
        }
        try {
            // 先判断文件不为空
            if (uploadFiles != null && uploadFiles.length > 0) {
                //循环遍历，取出单个文件
                for (MultipartFile uploadFile : uploadFiles) {
                    String contentType = uploadFile.getContentType();
                    String[] strings = contentType.split("/");
                    if (strings.length>0){
                        map.put("fileType",strings[0]);
                    }
                    if (!uploadFile.isEmpty()) {
                        String fileName = "";

                        String storePath;
                        if (classification!=null && classification.equals("test")){
                            storePath = uploadTestPath +"/xlgw/test/" + type + File.separator;
                        }else {
                            storePath = uploadFilePath + "/xlgw/resources/"+type + File.separator;
                        }
                        File dir = new File(storePath);
                        if (!dir.isDirectory()) {
                            dir.mkdirs();
                        }
                        String fileOriginalName = uploadFile.getOriginalFilename();
                        String newFileName = new Date().getTime() + UUID.randomUUID().toString().replace("-", "").substring(1, 6) + fileOriginalName.substring(fileOriginalName.lastIndexOf("."));
                        File file = new File(storePath + newFileName);
                        uploadFile.transferTo(file);
                        Encoder encoder = new Encoder();
                        MultimediaInfo m = encoder.getInfo(file);
                        long ms = 0;
                        ms = m.getDuration();
                        String timeMs = ReadVideoTimeMs(ms);
                        map.put("timeMs",timeMs);
                        if (classification!=null && classification.equals("test")){
                            fileName += "/test/" + type + "/" + newFileName;
                        }else {
                            fileName += "/resources/" + type + "/" + newFileName;
                        }
                        urlList.add(fileName);
                    }
                }
                map.put("fileList", urlList);
                map.put("type",Integer.parseInt(type));
                reData.setData(map);
            } else {
                reData.setCode(-1);
                reData.setMsg("资源文件为空，请选择文件!");
                return reData;
            }
        } catch (Exception e) {
            e.printStackTrace();
            reData.setCode(-1);
            reData.setMsg("资源文件保存失败!");
            return reData;
        }
        logger.info("=====================uploadFile end=========================");
        return reData;
    }

    @RequestMapping(value = "/deleteFile",method =  RequestMethod.POST)
    public ResponseData deleteFile(@RequestParam String uuid, @RequestParam String type,
                                   String classification) {
        ResponseData responseData = new ResponseData();
        return null;
    }


    public String ReadVideoTimeMs(long ms ) {
        int ss = 1000;
        int mi = ss * 60;
        int hh = mi * 60;
        int dd = hh * 24;
        long day = ms / dd;
        long hour = (ms - day * dd) / hh;
        long minute = (ms - day * dd - hour * hh) / mi;
        long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        String strHour = hour < 10 ? "0" + hour : "" + hour;//小时
        String strMinute = minute < 10 ? "0" + minute : "" + minute;//分钟
        String strSecond = second < 10 ? "0" + second : "" + second;//秒
        if (strHour.equals("00")) {
            return strMinute + ":" + strSecond;
        } else {
            return strHour + ":" + strMinute + ":" + strSecond;
        }
    }
}
